package com.myself.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * Description:
 *
 * @Author: Liuzemin
 * @Date: 2020/7/13 10:32
 */
@Controller
public class LoginController {
    /**
     * 用户登录的入口
     *
     * @param username
     * @param password
     * @param model
     * @return
     */
    @RequestMapping("/login")
    public String login(
            @RequestParam(value = "username", required = false) String username,
            @RequestParam(value = "password", required = false) String password,
            @RequestParam(value = "remember", required = false) String remember,
            Model model) {

        System.out.println("用户名：" + username + "密码：" + password);
        String error = null;
        if (username != null && password != null){
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            if (remember != null){
                if (remember.equals("on")){
                    token.setRememberMe(true);
                }else {
                    token.setRememberMe(false);
                }
            }else {
                token.setRememberMe(false);
            }

            try {
                subject.login(token);
                System.out.println("用户是否登录" + subject.isAuthenticated());
                return "redirect:index.jsp";
            }catch (Exception e){
                e.printStackTrace();
                error = "出现错误";
            }
        }else {
            error = "登录失败";
        }
        model.addAttribute("error", error);
        return "login";
    }

    @RequestMapping("/index")
    public String index(){
        return "index";
    }
}
